<?php

namespace app\api\controller;

use app\api\service\JwtAuth;
use app\common\service\UrlServer;
use think\facade\Filesystem;

class Upload extends Base
{
    protected $middleware = [
        'app\api\middleware\Api' => ['except' => ['upImage']],
    ];

    public function upImage()
    {
        $file = request()->file('file');

        // 验证规则
        if (!$file) {
            return $this->result([
                'code' => 0,
                'cid' => 0,
                'msg' => 'ERROR: 未找到上传的文件',
                'url' => ''
            ], 0, -1, '上传失败');
        }

        $savename = Filesystem::disk('public')->putFile('uploads', $file);
        // windows系统中路径反斜杠处理
        $savename = str_replace('\\', '/', $savename);

        if ($savename === false) {
            \think\facade\Log::record('ERROR: 文件保存失败', 'error');
            return $this->result([
                'code' => 0,
                'msg' => 'ERROR: 文件保存失败',
                'url' => ''
            ], 0, -1, '上传失败');
        }

        return $this->result([
            'code' => 1,
            'msg' => '上传成功',
            'url' => '/' . $savename,
            'uri' => UrlServer::getFileUrl($savename),
            'cid' => 0,
            'type' => 'image',
        ], 1, 1, '上传成功');

    }

    public function image()
    {

        $file = request()->file('file');
        $user_id = JwtAuth::getInstance()->getUserId();


        // 验证规则
        if (!$file) {
            return $this->result([
                'code' => 0,
                'cid' => 0,
                'source_id' => $user_id,
                'msg' => 'ERROR: 未找到上传的文件',
                'url' => ''
            ], 0, -1, '上传失败');
        }


        $savename = Filesystem::disk('public')->putFile('uploads', $file);
        // windows系统中路径反斜杠处理
        $savename = str_replace('\\', '/', $savename);

        if ($savename === false) {
            \think\facade\Log::record('ERROR: 文件保存失败', 'error');
            return $this->result([
                'code' => 0,
                'msg' => 'ERROR: 文件保存失败',
                'url' => ''
            ], 0, -1, '上传失败');
        }

        return $this->result([
            'code' => 1,
            'msg' => '上传成功',
            'url' => '/' . $savename,
            'uri' => UrlServer::getFileUrl($savename),
            'cid' => 0,
            'type' => 'image',
        ], 1, 1, '上传成功');

    }

}